#!/usr/bin/env python
#coding:utf-8

import tornado
from ..baseHandler import BaseHandler
from bson import ObjectId
from ..error import ErrorHandler
import datetime

class CollectionHandler(BaseHandler):


    @tornado.gen.coroutine
    def get(self,userId):
        if not userId:
            return ErrorHandler.write_error(self,status_code=101,message="缺少用户ID信息")
        try:
            objectId = ObjectId(userId)
        except Exception as e:
            return  ErrorHandler.write_error(self,status_code=102,message=str(e))
        #获取用户的收藏
        collections = yield self.db.user_collection.find({"user":userId}).to_list(10)
        if not collections:
            return self.response_msg(200,"该用户暂无收藏信息",[{}])
        #获取收藏的信息，对数据进行解析，主要是查找item的具体信息
        else:
            for i in range(len(collections)):
                #寻找所有收藏的详细信息
                collections[i]['item_detail'] = yield self.getCollectionDetailItem(collections[i]['collection_type'],collections[i]['item'])
                #解决json解析ObjectId类型的错误
                collections[i]['item_detail']["objectId"] = str(collections[i]['item_detail']["_id"])
                del collections[i]['item_detail']["_id"]
                #关于drug评分的问题待解决
                #TODO
                #关于drug价格问题待解决
            return self.response_msg(200,"成功",self.find_formart(collections))


    @tornado.gen.coroutine
    def getCollectionDetailItem(self,type,item):
        if type == 'drug':
            res = yield self.db.drug.find_one({'_id':ObjectId(item)},{'_id':1,"name":1,"introductions.生产企业":1,"images":1})
            return res

    #用户添加收藏接口
    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        (arguments,error) = yield self.get_select_argument(['user','collection_type','item'])
        if error:
            return ErrorHandler.write_error(self,status_code=103,message=error)
        #处理插入逻辑
        arguments['created_at'] = datetime.datetime.utcnow()
        #判断收藏类型,暂定只支持drug
        if arguments['collection_type'] != 'drug':
            return ErrorHandler.write_error(self,status_code=107,message="不支持的收藏类型")
        #查找是否已经收藏过这个item
        refer = yield self.db.user_collection.find_one({"user":arguments['user'],
                                                        "item":arguments['item'],
                                                        "collection_type":arguments['collection_type']})
        if refer:
            #如果已经收藏了，哪就取消收藏
            res = yield self.db.user_collection.remove({"_id":refer['_id']})
            if res:
                return self.response_msg(200,"取消收藏成功")
            else:
                return ErrorHandler.write_error(self,status_code=106,message="取消收藏失败")
        else:
            #如果没有找到记录，则直接添加收藏
            res = yield self.db.user_collection.insert(arguments)
            if not res:
                return ErrorHandler.write_error(self,status_code=104,message="收藏失败")
            else:
                return self.response_msg(200,"收藏成功")



handlers = [(r"/collection/(.*)",CollectionHandler),
            (r"/collection",CollectionHandler),
            ]